import type { NextApiRequest, NextApiResponse } from "next";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === "GET") {
    const imgName = req.query.imgName as string;
    getImage(imgName, res);
  }
}

function getImage(imgName: string, res: NextApiResponse) {
  const uploadDir = path.join(process.cwd(), "upload");
  const imgPath = path.join(uploadDir, imgName);
  const stream = fs.createReadStream(imgPath);
  stream.on("data", (chunk) => {
    res.write(chunk);
  });
  stream.on("end", () => {
    res.status(200).end();
  });
}
